package com.fingard.dsp.bank.directbank.gynsh01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.gynsh01.util.JsonHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import java.util.Date;

/**
 * @Description TODO
 * @Author xtt
 * @Date $ $
 **/
public class GYNSH01Base extends DirectBase {

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime17Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected String sendToBank(String data,String transType,String commandCode) throws Exception {
        String[] retStr = new String[]{"", ""};
        //后置挡板
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, data, retStr);
            if (retStr.length > 0) {
                return retStr[1];
            }
        }
        return sendToBank(data);
    }

    public String sendToBank(String data) throws Exception{
        HttpPost httpPost = new HttpPost(bankFront.getUrl("POST"));
        StringEntity dataEntity = new StringEntity((String) data, ContentType.APPLICATION_JSON);
        httpPost.setEntity(dataEntity);
        String str = JsonHelper.postSend(bankFront.getUrl("POST"),data);
        WriteBankLogLn("2.解密前返回的报文：" + str);
        String resp = JsonHelper.decrypted(str,getBankConfig().getValueAsString("privateKeyMerchant"));
        WriteBankLogLn("2.银行返回信息：" + resp);
        return resp;
    }

    public JSONObject createHead(String tradeCode) {
        JSONObject headObj = new JSONObject();
        headObj.put("version",1.0);
        headObj.put("source","pos");
        headObj.put("trade_code", tradeCode);

        headObj.put("mch_no",getBankConfig().getValueAsString("mchNo"));
        headObj.put("shop_no",getBankConfig().getValueAsString("shopNo"));

        headObj.put("out_trade_no",getQryTransID());
        headObj.put("trade_time",Format.DateTime14Format.format(new Date()));
        headObj.put("trade_date",Format.Date8Format.format(new Date()));
        return headObj;
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }
}
